<template>
  <div>
    <ProductionList :list='productionList'></ProductionList>
    <br />
    <CartList :productionList='productionList' :cartList='cartList'></CartList>
  </div>
</template>

<script>
import ProductionList from './ProductionList/index'
import CartList from './CartList/index.vue'
import event from './event'
export default {
  components: {
    ProductionList,
    CartList
  },
  mounted() {
    event.$on('addToCart', this.addToCart)
    event.$on('delFromCart', this.delFromCart)
  },
  data() {
    return {
      productionList: [
        {
          id: 1,
          title: '商品A',
          price: 10
        },
        {
          id: 2,
          title: '商品B',
          price: 15
        },
        {
          id: 3,
          title: '商品C',
          price: 20
        }
      ],
      cartList: [
        {
          id: 1,
          quantity: 1 // 购物数量
        }
      ]
    }
  },
  methods: {
    addToCart(id) {
      const prd = this.cartList.find(item => {
        return item.id === id
      })
      if (prd) {
        prd.quantity++
        return
      }
      this.cartList.push({
        id,
        quantity: 1
      })
    },
    delFromCart(id) {
      const prd = this.cartList.find(item => item.id === id)
      if (prd === null) {
        return
      }
      prd.quantity--
      if (prd.quantity <= 0) {
        this.cartList = this.cartList.filter(item => {
          return item.id !== id
        })
      }
    }
  }
}
</script>

<style>
</style>
